package com.zipeng.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zipeng.redis_interface.FunctionEntityCache;
import com.zipeng.redis_interface.FunctionListCache;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CacheService {
    @Autowired
    private RedisService redisService;

    //从缓存中获取实体对象
    public <T> T getEntityCache(String key, Long timeout, Class<T> cla, FunctionEntityCache<T> function) {
        //返回的实体
        T obj = null;
        //1.根据key取出缓存中的key
        //2.判断缓存中的数据是否存在，存在则返回，不存在则查询数据库
        String value = redisService.get(key);
        if (StringUtils.isEmpty(value)) { //缓存中数据不存在，查询数据库
            obj = function.getCache();
            if (obj != null) {
                String seach = JSONObject.toJSONString(obj);
                redisService.set(key, seach, timeout);
            } else {
                redisService.set(key, null, 60000);
            }

        } else { //缓存中存在，直接返回
            obj = JSON.parseObject(value, cla);
        }
        return obj;
    }

    //从缓存中获取list
    public <T> List<T> getListCache(String key, Long timeout, Class<T> cla, FunctionListCache<T> function) {
        List<T> list = null;
        String value = redisService.get(key);
        if (StringUtils.isEmpty(value)) {
            list = function.getCache();
            if (list.isEmpty()) {
                redisService.set(key, null, 60000);
            } else {
                String val = JSONObject.toJSONString(list);
                redisService.set(key, val, timeout);
            }

        } else {
            list = JSON.parseArray(value, cla);
        }
        return list;
    }
}
